package article;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import flux.RSSReader;

public class ArticleXML extends Article {
	
	public ArticleXML() {
		super();
	}
	
	public ArticleXML(String titre, String date, String provenance, String auteur, String contenue) {
		super(titre,date,provenance,auteur,contenue);
	}
	
	public ArticleXML(Node node){
		super();
		Element element = null;
		element = (Element) node;
		this.setTitre(readNode(element, "title").trim());
        this.setDate(GMTDateToFrench(readNode(element, "pubDate")).trim());
        if(!readNode(element, "author").equals(null) && !readNode(element, "author").equals("")){
        	this.setAuteur(readNode(element, "author").trim());
        }
        else{
        	this.setAuteur("inconnu");
        }
        this.setContenu(readNode(element, "description").trim());
        this.setProvenance(readNode(element, "link").trim());
	}
	
	public String readNode(Node _node, String _path) {

        String[] paths = _path.split("\\|");
        Node node = null;

        if (paths != null && paths.length > 0) {
            node = _node;

            for (int i = 0; i < paths.length; i++) {
                node = getChildByName(node, paths[i].trim());
            }
        }

        if (node != null) {
            return node.getTextContent();
        } else {
            return "";
        }
    }
	
	public Node getChildByName(Node _node, String _name) {
        if (_node == null) {
            return null;
        }
        NodeList listChild = _node.getChildNodes();

        if (listChild != null) {
            for (int i = 0; i < listChild.getLength(); i++) {
                Node child = listChild.item(i);
                if (child != null) {
                    if ((child.getNodeName() != null && (_name.equals(child.getNodeName()))) || (child.getLocalName() != null && (_name.equals(child.getLocalName())))) {
                        return child;
                    }
                }
            }
        }
        return null;
    }
	
	public String GMTDateToFrench(String gmtDate) {
        try {
            SimpleDateFormat dfGMT = new SimpleDateFormat("EEE, dd MMM yy HH:mm:ss z", Locale.ENGLISH);
            dfGMT.parse(gmtDate);
            SimpleDateFormat dfFrench = new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE);
            return dfFrench.format(dfGMT.getCalendar().getTime());
        } catch (ParseException ex) {
            Logger.getLogger(RSSReader.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "";
    }

	
}
